package com.fas.hehe.system.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.junit.Assert;

import com.fas.core.BaseService;
import com.fas.core.plugin.datatables.PageRequest;
import com.fas.hehe.system.model.Role;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

public class RoleService extends BaseService {
	
	 public Page<Record> queryPage(PageRequest request){
         Assert.assertNotNull("请求参数不能为空", request);
         
         Map<String,Object> paramsMap = request.getParams();
         ArrayList<Object> params = new ArrayList<Object>();
         String selectSql = "select * ";
         StringBuffer whereSql = new StringBuffer();
         whereSql.append(" from sys_role where 1=1 ");
         
         if(StrKit.notBlank((String)paramsMap.get("id"))){
                 whereSql.append(" and id = ?");
                 params.add(paramsMap.get("id"));
         }
         if(StrKit.notBlank((String)paramsMap.get("role"))){
                 whereSql.append(" and role like ?");
                 params.add(this.getLikeValue(paramsMap.get("role")));
         }
         
         if(StrKit.notBlank((String)request.getOderby())){
                 whereSql.append(" order by ").append(request.getOderby()) ;
         }
         
         return Db.paginate(request.getPageNumber(), request.getPageSize(), selectSql, whereSql.toString(),params.toArray());
 }
 
 
	// 根据角色编号得到角色标识符列表
	public Set<String> findRoles(Long... roleIds) {
		Set<String> roles = new HashSet<String>();
		for (Long roleId : roleIds) {
			Role role = findOne(roleId);
			if (role != null) {
				roles.add(role.getStr("role"));
			}
		}
		return roles;
	}

	// 根据角色编号得到权限字符串列表
	public Set<String> findPermissions(Long[] roleIds) {
		Set<Long> resourceIds = new HashSet<Long>();
		for (Long roleId : roleIds) {
			Role role = findOne(roleId);
			if (role != null) {
				String resourceIdsStr = role.getStr("resource_ids");
				String[] resourceIdStrs = resourceIdsStr.split(",");
				for (String resourceIdStr : resourceIdStrs) {
					if (StringUtils.isEmpty(resourceIdStr)) {
						continue;
					}
					resourceIds.add(Long.valueOf(resourceIdStr));
				}
			}
		}
		return new ResourceService().findPermissions(resourceIds);
	}

	public Role findOne(Long roleId) {
		return Role.dao.findById(roleId);
	}

	public List<Role> findAll() {
		final String sql = "select id, role, description, resource_ids as resourceIdsStr, available from sys_role";
		return Role.dao.find(sql);
	}
}
